package com.weimob.mcloud.wechatwork.customer.job;

import com.alibaba.fastjson.JSON;
import com.weimob.elasticjob.annotation.ElasticJob;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.request.WidCreateReq;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.response.WidCreateBO;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.enums.group.RetryStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.group.request.CustomerGroupMemberDTO;
import com.weimob.mcloud.wechatwork.core.service.group.request.CustomerGroupWidCreateRecordDTO;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.onecrm.OneCrmProxy;
import com.weimob.mcloud.wechatwork.customer.mq.model.CorpChatGroupServiceImpl;
import com.weimob.mcloud.wechatwork.customer.mq.model.CustomerGroupMemberList;
import com.weimob.mcloud.wechatwork.customer.service.impl.ArtemisService;
import com.weimob.mcloud.wechatwork.customer.service.user.base.BasicInfo;
import com.weimob.mcloud.wechatwork.customer.third.PrivateSphereThird;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerGroupExportServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;


@Slf4j
@Component
public class CustomerGroupFailRetryJob {
    @Resource
    private ArtemisService artemisService;

    @Resource
    private OneCrmProxy oneCrmProxy;

    @Autowired
    private CorpChatGroupServiceImpl corpChatGroupService;

    @Autowired
    private PrivateSphereThird privateSphereThird;

    @Autowired
    private CustomerGroupExportServiceProxy customerGroupExportServiceProxy;

    /**
     * 同步群成员时需要向passport送wid,passport接口不稳定（超时，限频）
     * 对于送passport失败的数据，落推送记录表，该job作用为对失败数据进行补偿
     */
    @ElasticJob(name = "pushFailRetryJob", cron = "0 0/10 * * * ?")
    public void pushFailRetryJob() {
        log.info("送wid到passport失败补偿开始");
        CustomerGroupWidCreateRecordDTO recordDTO = new CustomerGroupWidCreateRecordDTO();
        recordDTO.setStatus(RetryStatusEnum.WAIT_RETRY);
        //最大循环次数，防止死循环
        int maxLoop = 1000;
        int currentLoop = 1;
        MultiResponse<CustomerGroupWidCreateRecordDTO> multiResponse;
        do {
            multiResponse = customerGroupExportServiceProxy.batchFetchWidCreateRecord(recordDTO, true, 1, 100);
            List<CustomerGroupWidCreateRecordDTO> dataList = multiResponse.getDataList();
            // 未查到数据 结束循环
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            for (CustomerGroupWidCreateRecordDTO dto : dataList) {
                // 将群成员中客户数据送到passPort
                WidCreateReq widCreateReq = new WidCreateReq();
                widCreateReq.setBosId(dto.getBosId());
                widCreateReq.setCorpId(dto.getCorpId());
                widCreateReq.setExternalUserId(dto.getExternalUserId());
                widCreateReq.setUnionId(dto.getUnionId());
                widCreateReq.setNickname(dto.getNickname());
                WidCreateBO widCreateBO = oneCrmProxy.createWid(widCreateReq);
                if (Objects.nonNull(widCreateBO)) {
                    // 送passport成功修改状态
                    dto.setStatus(RetryStatusEnum.SUCCESS);
                    customerGroupExportServiceProxy.updateWidCreateRecord(dto);
                    // 发送wid创建完成消息
                    String completeMsg = dto.getCompletedMsg();
                    if (StringUtils.isNotBlank(completeMsg)) {
                        ArtemisBaseInfo artemisBaseDomain = new ArtemisBaseInfo();
                        artemisBaseDomain.setTopic(ArtemisConstant.Topic.WECHATWORK_GROUP_MEMBER_UPDATE_MSG);
                        artemisBaseDomain.setProducer(ArtemisConstant.USER);
                        artemisBaseDomain.setEvent(completeMsg);
                        artemisService.sendStringEventToArtemis(artemisBaseDomain);
                        // 客户入群消息二次分发 对接开放平台
                        sendSecondMsg(widCreateBO, completeMsg);
                    }
                }
            }
            currentLoop++;
        } while (currentLoop <= maxLoop);
        log.info("送wid到passport失败补偿结束");
    }

    /**
     * 客户入群消息二次分发 对接开放平台
     * @param widCreateBO
     * @param completeMsg
     */
    private void sendSecondMsg(WidCreateBO widCreateBO, String completeMsg) {
        try{
            if(Objects.isNull(widCreateBO) || StringUtils.isBlank(completeMsg)){
                return;
            }
            CustomerGroupMemberList customerGroupMemberList = JSON.parseObject(completeMsg, CustomerGroupMemberList.class);
            List<CustomerGroupMemberDTO> members = customerGroupMemberList.getMembers();
            if (CollectionUtils.isEmpty(members)) {
                return;
            }
            CustomerGroupMemberDTO memberDTO = members.get(0);
            BasicInfo basicInfo = new BasicInfo();
            basicInfo.setCorpId(memberDTO.getCorpId());
            PrivateSphere privateSphere = privateSphereThird.fetch(basicInfo,true);
            corpChatGroupService.customerJoinGroupSecondMsg(memberDTO, privateSphere, widCreateBO.getWid());
        }catch (Exception e){
            log.error("CustomerGroupFailRetryJob.sendSecondMsg error: ",e);
        }
    }

    /**
     * 定期清理推送记录表数据
     * 将重试成功推送passport的数据清除，防止表数据量过大
     */
    @ElasticJob(name = "clearRetrySuccessRecord", cron = "0 0 0 1 * ?")
    public void clearRetrySuccessRecord() {
        CustomerGroupWidCreateRecordDTO dto = new CustomerGroupWidCreateRecordDTO();
        dto.setStatus(RetryStatusEnum.SUCCESS);
        customerGroupExportServiceProxy.deleteWidCreateRecord(dto);
    }

}